/*
 * @Author: 黑白灰01 3193273703@qq.com
 * @Date: 2025-01-27 13:18:02
 * @LastEditors: 黑白灰01 3193273703@qq.com
 * @LastEditTime: 2025-02-13 18:47:15
 * @FilePath: /hei_picture_web/src/stores/userLoginStore.ts
 * @Description: 用户登录信息状态
 */
import { getLoginUserUsingGet } from '@/api/userController'
import { defineStore } from 'pinia'
import { ref } from 'vue'
type LoginUserInfo = {
  userName: string
  userId: string | null
  userAvatar: string | null
  userRole: string | null
}
// 导出一个名为useLoginUserStore的函数，用于定义登录用户的信息存储
export const useLoginUserStore = defineStore('loginUser', () => {
  const loginUserInfo = ref<LoginUserInfo>({
    userName: '',
    userId: null,
    userAvatar: null,
    userRole: null,
  })
  const isLoaded = ref(false)

  const fetchLoginUserInfo = async () => {
    if (isLoaded.value && loginUserInfo.value.userId) {
      return // 如果已经加载过且有用户ID，直接返回
    }

    try {
      const { data } = await getLoginUserUsingGet({})
      if (data.code === 200) {
        loginUserInfo.value.userId = data.data?.id ?? null
        loginUserInfo.value.userName = data.data?.userName ?? ''
        loginUserInfo.value.userAvatar = data.data?.userAvatar ?? null
        loginUserInfo.value.userRole = data.data?.userRole ?? null
        isLoaded.value = true
      } else {
        isLoaded.value = false
      }
    } catch (error) {
      console.error('Failed to fetch user info:', error)
      isLoaded.value = false
    }
  }

  const setLoginUserInfo = (userInfo: LoginUserInfo) => {
    loginUserInfo.value = userInfo
    isLoaded.value = true
  }

  return {
    loginUserInfo,
    fetchLoginUserInfo,
    setLoginUserInfo,
    isLoaded,
  }
})
